//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import { observer } from 'mobx-react';
import { TreeSelect } from 'antd';
import { DefaultOptionType } from 'antd/lib/select';
import { useStores } from '@/hooks';
import { useHistory, useLocation } from 'react-router-dom';
import { APP_EXTERN_PAGE_PATH, APP_ORG_MANAGER_PATH, APP_ORG_PATH, APP_PROJECT_HOME_PATH, APP_PROJECT_MANAGER_PATH, DATA_VIEW_PATH, GROW_CENTER_PATH, PUB_RES_PATH, WORKBENCH_PATH } from '@/utils/constant';
import { PROJECT_HOME_CONTENT_LIST } from '@/api/project';
import { open as shell_open } from '@tauri-apps/api/shell';

const AppNavigator = () => {
    const location = useLocation();
    const history = useHistory();

    const appStore = useStores('appStore');
    const userStore = useStores('userStore');
    const projectStore = useStores('projectStore');
    const orgStore = useStores('orgStore');
    const entryStore = useStores('entryStore');


    const [treeData, setTreeData] = useState<DefaultOptionType[]>([]);
    const [treeValue, setTreeValue] = useState("workbench");

    const onChange = (value: string) => {
        if (value == "workbench") {
            if (appStore.inEdit) {
                appStore.showCheckLeave(() => {
                    history.push(WORKBENCH_PATH);
                    projectStore.setCurProjectId("");
                    orgStore.setCurOrgId("");
                    appStore.curExtraMenu = null;
                });
            } else {
                history.push(WORKBENCH_PATH);
                projectStore.setCurProjectId("");
                orgStore.setCurOrgId("");
                appStore.curExtraMenu = null;
            }
        } else if (value == "dataview") {
            if (appStore.inEdit) {
                appStore.showCheckLeave(() => {
                    history.push(DATA_VIEW_PATH);
                    projectStore.setCurProjectId("");
                    orgStore.setCurOrgId("");
                    appStore.curExtraMenu = null;
                });
            } else {
                history.push(DATA_VIEW_PATH);
                projectStore.setCurProjectId("");
                orgStore.setCurOrgId("");
                appStore.curExtraMenu = null;
            }
        } else if (value == "projectmgr") {
            if (appStore.inEdit) {
                appStore.showCheckLeave(() => {
                    projectStore.setCurProjectId("");
                    orgStore.setCurOrgId("");
                    appStore.curExtraMenu = null;
                    history.push(APP_PROJECT_MANAGER_PATH);
                });
            } else {
                projectStore.setCurProjectId("");
                orgStore.setCurOrgId("");
                appStore.curExtraMenu = null;
                history.push(APP_PROJECT_MANAGER_PATH);
            }
        } else if (value.startsWith("project:")) {
            const projectId = value.substring("project:".length);
            if (appStore.inEdit) {
                appStore.showCheckLeave(() => {
                    projectStore.setCurProjectId(projectId).then(() => {
                        entryStore.reset();
                        appStore.curExtraMenu = null;
                        projectStore.projectHome.homeType = PROJECT_HOME_CONTENT_LIST;
                        history.push(APP_PROJECT_HOME_PATH);
                        orgStore.setCurOrgId("");
                    });
                });
            } else {
                projectStore.setCurProjectId(projectId).then(() => {
                    entryStore.reset();
                    appStore.curExtraMenu = null;
                    projectStore.projectHome.homeType = PROJECT_HOME_CONTENT_LIST;
                    history.push(APP_PROJECT_HOME_PATH);
                    orgStore.setCurOrgId("");
                });
            }
        } else if (value == "orgmgr") {
            if (appStore.inEdit) {
                appStore.showCheckLeave(() => {
                    projectStore.setCurProjectId("");
                    orgStore.setCurOrgId("");
                    appStore.curExtraMenu = null;
                    history.push(APP_ORG_MANAGER_PATH);
                });
            } else {
                projectStore.setCurProjectId("");
                orgStore.setCurOrgId("");
                appStore.curExtraMenu = null;
                history.push(APP_ORG_MANAGER_PATH);
            }
        } else if (value.startsWith("org:")) {
            const orgId = value.substring("org:".length);
            if (appStore.inEdit) {
                appStore.showCheckLeave(() => {
                    orgStore.setCurOrgId(orgId).then(() => {
                        projectStore.setCurProjectId("");
                        appStore.curExtraMenu = null;
                        history.push(APP_ORG_PATH);
                    });
                });
            } else {
                orgStore.setCurOrgId(orgId).then(() => {
                    projectStore.setCurProjectId("");
                    appStore.curExtraMenu = null;
                    history.push(APP_ORG_PATH);
                });
            }
        } else if (value == "pubres") {
            if (appStore.inEdit) {
                appStore.showCheckLeave(() => {
                    history.push(PUB_RES_PATH);
                    projectStore.setCurProjectId("");
                    orgStore.setCurOrgId("");
                    appStore.curExtraMenu = null;
                });
            } else {
                history.push(PUB_RES_PATH);
                projectStore.setCurProjectId("");
                orgStore.setCurOrgId("");
                appStore.curExtraMenu = null;
            }
        } else if (value == "growcenter") {
            if (appStore.inEdit) {
                appStore.showCheckLeave(() => {
                    history.push(GROW_CENTER_PATH);
                    projectStore.setCurProjectId("");
                    orgStore.setCurOrgId("");
                    appStore.curExtraMenu = null;
                });
            } else {
                history.push(GROW_CENTER_PATH);
                projectStore.setCurProjectId("");
                orgStore.setCurOrgId("");
                appStore.curExtraMenu = null;
            }
        } else if (value.startsWith("servmenu:")) {
            const menuId = value.substring("servmenu:".length);
            const menu = (appStore.clientCfg?.item_list ?? []).find(item => item.menu_id == menuId);
            if (menu != undefined) {
                if (menu.open_in_browser) {
                    shell_open(menu.url);
                } else {
                    projectStore.setCurProjectId("");
                    orgStore.setCurOrgId("");
                    appStore.curExtraMenu = menu;
                    history.push(APP_EXTERN_PAGE_PATH);
                }
            }
        } else if (value.startsWith("localmenu:")) {
            const menuId = value.substring("localmenu:".length);
            const menu = (appStore.vendorCfg?.layout.menu_list ?? []).find(item => item.id == menuId);
            if (menu != undefined) {
                projectStore.setCurProjectId("");
                orgStore.setCurOrgId("");
                appStore.curExtraMenu = {
                    name: menu.name,
                    url: menu.url,
                    menu_id: menu.id,
                    weight: 0,
                    main_menu: true,
                    open_in_browser: false,
                };
                history.push(APP_EXTERN_PAGE_PATH);
            }
        }
    };

    const calcTreeData = () => {
        const tmpTreeData: DefaultOptionType[] = [];
        if (appStore.vendorCfg?.ability.enable_work_bench == true) {
            tmpTreeData.push({
                label: <span style={{ fontWeight: 700 }}>工作台</span>,
                value: "workbench"
            });
        }

        if (userStore.sessionId != "") {
            if (appStore.vendorCfg?.ability.enable_dataview && userStore.userInfo.featureInfo.enable_data_view) {
                tmpTreeData.push({
                    label: <span style={{ fontWeight: 700 }}>数据视图</span>,
                    value: "dataview",
                });
            }
            if (appStore.vendorCfg?.ability.enable_project && userStore.userInfo.featureInfo.enable_project) {
                tmpTreeData.push({
                    label: <span style={{ fontWeight: 700 }}>项目管理</span>,
                    value: "projectmgr",
                });
                const prjList: DefaultOptionType[] = [];
                for (const prj of projectStore.projectList) {
                    prjList.push({
                        label: <span style={{ color: prj.closed ? "grey" : "black", fontWeight: prj.closed ? 100 : 700 }}>{prj.basic_info.project_name}</span>,
                        value: `project:${prj.project_id}`,
                    });
                }
                if (prjList.length > 0) {
                    tmpTreeData.push({
                        label: "项目列表",
                        value: "projectlist",
                        children: prjList,
                        disabled: true,
                    });
                }
            }
            if (appStore.vendorCfg?.ability.enable_org && userStore.userInfo.featureInfo.enable_org) {
                tmpTreeData.push({
                    label: <span style={{ fontWeight: 700 }}>团队管理</span>,
                    value: "orgmgr",
                });
                const orgList: DefaultOptionType[] = [];
                for (const org of orgStore.orgList) {
                    orgList.push({
                        label: <span style={{ fontWeight: 700 }}>{org.basic_info.org_name}</span>,
                        value: `org:${org.org_id}`,
                    });
                }
                if (orgList.length > 0) {
                    tmpTreeData.push({
                        label: "团队列表",
                        value: "orglist",
                        children: orgList,
                        disabled: true,
                    });
                }
            }
        }
        if (appStore.vendorCfg?.ability.enable_pubres) {
            tmpTreeData.push({
                label: <span style={{ fontWeight: 700 }}>公共资源</span>,
                value: "pubres",
            });
        }
        if (appStore.vendorCfg?.ability.enable_grow_center && (userStore.userInfo.featureInfo.enable_grow_center || appStore.vendorCfg.grow_center.force_show)) {
            tmpTreeData.push({
                label: <span style={{ fontWeight: 700 }}>成长中心</span>,
                value: "growcenter",
            });
        }
        if (appStore.vendorCfg?.layout.enable_server_menu) {
            for (const menu of (appStore.clientCfg?.item_list ?? [])) {
                if (menu.main_menu == false) {
                    continue;
                }
                tmpTreeData.push({
                    label: <span style={{ fontWeight: 700 }}>{menu.name}</span>,
                    value: `servmenu:${menu.menu_id}`,
                });
            }
        }
        for (const menu of (appStore.vendorCfg?.layout.menu_list ?? [])) {
            tmpTreeData.push({
                label: <span style={{ fontWeight: 700 }}>{menu.name}</span>,
                value: `localmenu:${menu.id}`,
            });
        }

        setTreeData(tmpTreeData);
    };

    const calcTreeValue = () => {
        if (location.pathname.startsWith(WORKBENCH_PATH)) {
            setTreeValue("workbench");
        } else if (location.pathname.startsWith(DATA_VIEW_PATH)) {
            setTreeValue("dataview");
        } else if (location.pathname.startsWith(APP_PROJECT_MANAGER_PATH)) {
            setTreeValue("projectmgr");
        } else if (location.pathname.startsWith(APP_PROJECT_HOME_PATH)) {
            if (projectStore.curProjectId != "") {
                setTreeValue(`project:${projectStore.curProjectId}`);
            }
        } else if (location.pathname.startsWith(APP_ORG_MANAGER_PATH)) {
            setTreeValue("orgmgr");
        } else if (location.pathname.startsWith(APP_ORG_PATH) && location.pathname.startsWith(APP_ORG_MANAGER_PATH) == false) {
            if (orgStore.curOrgId != "") {
                setTreeValue(`org:${orgStore.curOrgId}`);
            }
        } else if (location.pathname.startsWith(PUB_RES_PATH)) {
            setTreeValue("pubres");
        } else if (location.pathname.startsWith(GROW_CENTER_PATH)) {
            setTreeValue("growcenter");
        } else if (location.pathname.startsWith(APP_EXTERN_PAGE_PATH)) {
            if (appStore.curExtraMenu != null) {
                if ((appStore.clientCfg?.item_list ?? []).map(item => item.menu_id).includes(appStore.curExtraMenu.menu_id)) {
                    setTreeValue(`servmenu:${appStore.curExtraMenu.menu_id}`);
                }
                if ((appStore.vendorCfg?.layout.menu_list ?? []).map(item => item.id).includes(appStore.curExtraMenu.menu_id)) {
                    setTreeValue(`localmenu:${appStore.curExtraMenu.menu_id}`);
                }
            }
        }
    };

    useEffect(() => {
        calcTreeData();
    }, [appStore.vendorCfg, projectStore.projectList, orgStore.orgList, userStore.userInfo.featureInfo]);

    useEffect(() => {
        calcTreeValue();
    }, [location.pathname, projectStore.curProjectId, orgStore.curOrgId, appStore.curExtraMenu]);


    return (
        <>
            {treeData.length <= 1 && (
                <div style={{ fontSize: "20px", marginLeft: "10px", fontWeight: 700 }}>{appStore.vendorCfg?.layout.app_name ?? ""}</div>
            )}
            {treeData.length > 1 && (
                <TreeSelect treeData={treeData} style={{ width: "150px", fontSize: "20px" }} treeExpandedKeys={["projectlist", "orglist"]}
                    value={treeValue} onChange={value => onChange(value)} />
            )}
        </>

    );
};

export default observer(AppNavigator);